package br.ufc.ck0017.ir.translate;

import br.ufc.ck0017.ir.tree.IR;
import br.ufc.ck0017.ir.tree.IRNode;
import br.ufc.ck0017.temp.Label;
import br.ufc.ck0017.temp.Temp;

public class IfThenElseExp extends TranslatedExpression {
    private final TranslatedExpression test;
    private final TranslatedExpression thenExp;
    private final TranslatedExpression elseExp;

    Label trueLabel = new Label("trueLabel");
    Label falseLabel = new Label("falseLabel");
    Label join = new Label("join");

    public IfThenElseExp(TranslatedExpression test, TranslatedExpression thenExp, TranslatedExpression elseExp) {
        this.test = test;
        this.thenExp = thenExp;
        this.elseExp = elseExp;
    }

    @Override
    public IRNode unEx()
    {
        Temp register = new Temp();
        return IR.ESEQ(IR.SEQ(IR.SEQ(test.unCx(trueLabel, falseLabel),
                                     IR.SEQ(IR.LABEL(trueLabel),
                                            IR.MOVE(IR.TEMP(register),
                                                    thenExp.unEx()))),
                              IR.SEQ(IR.LABEL(falseLabel),
                                     IR.MOVE(IR.TEMP(register),
                                             elseExp.unEx()))),
                       IR.TEMP(register));
    }

    @Override
    public IRNode unNx() {
        return IR.SEQ(IR.SEQ(test.unCx(trueLabel, falseLabel),
                             IR.SEQ(IR.SEQ(IR.LABEL(trueLabel), thenExp.unNx()), IR.JUMP(join))),
                      IR.SEQ(IR.SEQ(IR.SEQ(IR.LABEL(falseLabel), elseExp.unNx()), IR.JUMP(join)),
                             IR.LABEL(join)));
    }

    @Override
    public IRNode unCx(Label t, Label f) {
        return null;
    }
}
